# -*- coding: utf-8 -*-

import pytest

from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_service import AppiumService
from appium.webdriver.common.appiumby import AppiumBy

# 开启服务端
APPIUM_HOST = '127.0.0.1'
APPIUM_PORT = 4723
@pytest.fixture(scope="session")
def start_appium_service():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=60000)
    yield server
    server.stop()

APPIUM_PORT2 = 4724
@pytest.fixture(scope="session")
def start_appium_service2():
    server = AppiumService()
    server.start(args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT2)], timeout_ms=60000)
    yield server
    server.stop()

# 创建客户端到服务端的会话
def create_appium_session_by_api(custom_opts = None, appium_host = APPIUM_HOST, appium_port = APPIUM_PORT):
    options = UiAutomator2Options()
    if custom_opts is not None:
        options.load_capabilities(custom_opts)
    return webdriver.Remote(f'http://{appium_host}:{appium_port}', options=options)

def test_parallel_per_request(start_appium_service):
    custom_opts = {
        "appium:appPackage": "com.google.android.dialer",
        "appium:appActivity": ".extensions.GoogleDialtactsActivity",
        "appium:avd": "testPhone",
        "appium:systemPort": 8201,
    }

    custom_opts2 = {
        "appium:appPackage": "com.google.android.dialer",
        "appium:appActivity": ".extensions.GoogleDialtactsActivity",
        "appium:avd": "testPhone2",
        "appium:systemPort": 8202,
    }

    driver = create_appium_session_by_api(custom_opts)
    driver2 = create_appium_session_by_api(custom_opts2)

    contact_id_full = "com.google.android.dialer:id/tab_contacts"

    contact = driver.find_element(AppiumBy.ID, value=contact_id_full)
    contact2 = driver2.find_element(AppiumBy.ID, value=contact_id_full)

    contact.click()
    contact2.click()

    driver.quit()
    driver2.quit()

# 多服务端进程测试
def test_parallel_per_process(start_appium_service, start_appium_service2):
    custom_opts = {
        "appium:appPackage": "com.google.android.dialer",
        "appium:appActivity": ".extensions.GoogleDialtactsActivity",
        "appium:avd": "testPhone",
        "appium:systemPort": 8201,
    }

    custom_opts2 = {
        "appium:appPackage": "com.google.android.dialer",
        "appium:appActivity": ".extensions.GoogleDialtactsActivity",
        "appium:avd": "testPhone2",
        "appium:systemPort": 8202,
    }

    driver = create_appium_session_by_api(custom_opts, appium_port=APPIUM_PORT)
    driver2 = create_appium_session_by_api(custom_opts2, appium_port=APPIUM_PORT2)

    contact_id_full = "com.google.android.dialer:id/tab_contacts"

    contact = driver.find_element(AppiumBy.ID, value=contact_id_full)
    contact2 = driver2.find_element(AppiumBy.ID, value=contact_id_full)

    contact.click()
    contact2.click()

    driver.quit()
    driver2.quit()